package leecode

func solveSudoku(board [][]byte) {
	var backtracking func(board [][]byte) bool
	backtracking = func(board [][]byte) bool {
		for i := 0; i < 9; i++ { //遍历每一行
			for j := 0; j < 9; j++ { //遍历每一列
				//原始数字不去执行
				if board[i][j] != '.' {
					continue
				}
				for k := '1'; k <= '9'; k++ {
					//检查数字是否合格
					if isRight(i, j, byte(k), board) == true {
						board[i][j] = byte(k)
						if backtracking(board) == true {
							return true
						}
						board[i][j] = '.'
					}
				}
				//9组数据全部不符合
				return false
			}
		}
		return true
	}
	backtracking(board)
}

func isRight(row, column int, value byte, board [][]byte) bool {
	//当前行
	for i := 0; i < 9; i++ {
		if board[row][i] == value {
			return false
		}
	}
	//当前列
	for i := 0; i < 9; i++ {
		if board[i][column] == value {
			return false
		}
	}
	// 3 * 3
	threeStartRow, threeStartCoulmn := (row/3)*3, (column/3)*3 //3*3的开始行 开始列
	for i := threeStartRow; i < threeStartRow+3; i++ {
		for j := threeStartCoulmn; j < threeStartCoulmn+3; j++ {
			if board[i][j] == value {
				return false
			}
		}
	}
	return true
}
